<template>
  <div class="specs-info">
    <el-dialog
      :title="type == 'add' ? '新增' : '修改'"
      :visible.sync="isShow"
      width="60%"
      :before-close="close"
    >
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="属性名" prop="specsname">
          <el-input v-model="ruleForm.specsname"></el-input>
        </el-form-item>
        <el-form-item label="属性" prop="attrs">
          <div v-for="(item, index) in attrList" :key="index">
            <!-- 一个属性可以有多个属性值 需要循环生成过个输入框 -->
            <el-input class="attrs" v-model="attrList[index]"></el-input>
            <el-button type="danger" @click="delSpecs(index)">删除</el-button>
          </div>
          <el-button type="success" @click="addSpecs">添加</el-button>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addSpecs } from "../../apis";
export default {
  props: ["isShow", "type"],
  data() {
    return {
      // 属性值的数据，会根据数组的长度 生成不同的输入框
      attrList: [''],
      // 表单的数据
      ruleForm: {
        pid: 0,
        title: "",
        icon: "",
        url: "",
        type: 1,
        status: 1,
      },
    };
  },
  methods: {
    setVal(data) {
      // 给表单项赋值
      this.ruleForm = {...data};
      this.attrList = this.ruleForm.attrs;
    },
    close() {
      this.$emit("close");
    },
    addSpecs() {
      // 添加属性值的输入框
      this.attrList.push('')
    },
    delSpecs(index) {
      // 删除当前属性值
      this.attrList.splice(index, 1)
    },
    submit() {
      // 点击提交按钮
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.ruleForm.attrs = this.attrList.join(','); // 转换格式 后台需要字符串
          // 校验成功 可以提交数据了
          let res;
          // 先判断新增还是修改
          if(this.type == 'add') {
            res = await addSpecs(this.ruleForm);
          }else {
            res = await editMenu(this.ruleForm);
          }
          if (res.code == 200) {
            this.$emit("update");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
      this.close();
    },
  },
};
</script>

<style>
  .specs-info .attrs {
    width: 80%;
    margin-right: 20px;
    margin-left: 0;
    margin-bottom: 10px;
  }
</style>